package com.gx.controller;


import com.alibaba.fastjson.JSONObject;import com.gx.common.result.AppResult;
import com.gx.entity.dto.CreateJobTaskDto;
import com.gx.service.JobService;
import com.gx.utils.XxlJobUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * XxlJOBController
 *
 * @author Promsing(张有博)
 * @version 1.0.0
 * @since 2022/3/30 - 15:04
 */
@Api(tags = {"操作xxljob的业务类"})
@RequestMapping("/test")
@RestController
public class XxlJobController {
    @Autowired
    private JobService jobService;

    @ApiOperation(value = "添加jobInfo并启动")
    @PostMapping
    public AppResult<?> saveXxl(@RequestBody CreateJobTaskDto createJobTaskDto) {
        createJobTaskDto.setParam("123");
        createJobTaskDto.setExecutorHandler("SmsJobHandler");
        Integer taskId = jobService.saveTask(createJobTaskDto);
        return AppResult.success(taskId);
    }

    /**
     * 删除任务
     *
     * @param id 任务id
     * @return
     * @throws
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public AppResult delete(int id) {
        try {
            JSONObject res = XxlJobUtil.deleteJob(id);
            if (res.containsKey("code") && 200 == (Integer) res.get("code")) {
                return AppResult.success();
            } else {
                throw new Exception("调用xxl-job-admin-delete接口失败！");
            }
        } catch (Exception e) {
            return AppResult.failure("失败", 500);
        }

    }

    /**
     * 开始任务
     *
     * @param id 任务id
     * @return
     * @throws
     */
    @RequestMapping(value = "/start", method = RequestMethod.GET)
    public AppResult start(int id) {
        try {
            JSONObject result = XxlJobUtil.startJob(id);
            if (result.containsKey("code") && 200 == (Integer) result.get("code")) {
                return AppResult.success();
            } else {
                throw new Exception("调用xxl-job-admin-start接口失败！");
            }
        } catch (Exception e) {
            return AppResult.failure("失败", 500);
        }

    }

    /**
     * 挂起任务
     *
     * @param id 任务id
     * @return
     * @throws
     */
    @RequestMapping(value = "/stop", method = RequestMethod.GET)
    public AppResult stop(int id) {
        try {
            JSONObject res = XxlJobUtil.stopJob(id);
            if (res.containsKey("code") && 200 == (Integer) res.get("code")) {
                return AppResult.success();
            } else {
                throw new Exception("调用xxl-job-admin-stop接口失败！");
            }
        } catch (Exception e) {
            return AppResult.failure("失败", 500);
        }
    }

}